package com.polaris.live.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.popup.PublicTipsPopup
import com.polaris.live.translation.R

/**
 * OtherPermissionUtils
 *
 * @author Created by 天晴 on 2024/11/22 10:58
 * @since 1.0.0
 **/
object OtherPermissionUtils {

    var back: ((havePermission: Boolean) -> Unit)? = null //是否有在等待的回调

    fun hasOverlayPermission(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Settings.canDrawOverlays(context)
        } else {
            try {
                val method = Settings::class.java.getDeclaredMethod("canDrawOverlays", Context::class.java)
                method.invoke(null, context) as Boolean
            } catch (e: Exception) {
                e.printStackTrace()
                false
            }
        }
    }

    fun requestOverlayPermission(context: Context, back: (havePermission: Boolean) -> Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                val intent = Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:${context.packageName}")
                )
                if (context !is Activity) {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                context.startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
                ToastGravity.showGravity(StringUtils.getString(R.string.minimize_tips_no_permission))
            }
            this.back = back
        }
    }

    fun resumeActivity(context: Context) {
        back?.invoke(hasOverlayPermission(context))
        back = null
    }

    fun checkAndRequestOverlayPermission(
        context: Context,
        showDialog: Boolean = true,
        back: (havePermission: Boolean) -> Unit,
    ) {
        if (!hasOverlayPermission(context)) {
            if (showDialog) {
                PublicTipsPopup.show(
                    context, null,
                    StringUtils.getString(R.string.prompt),
                    StringUtils.getString(R.string.minimize_tips_permission),
                    StringUtils.getString(R.string.sure),
                    StringUtils.getString(R.string.cancel),
                    onTop = {
                        requestOverlayPermission(context, back)
                    },
                    onBottom = {
                        back.invoke(false)
                    }
                )
            } else {
                requestOverlayPermission(context, back)
            }
        } else {
            back.invoke(true)
        }
    }
}